package com.shop.item.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.shop.common.entity.item.ItemBase;
import com.shop.common.model.InputBean;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.item.ItemBaseInput;
import com.shop.common.model.result.item.ItemBaseOutput;
import com.shop.common.tmpl.BaseService;
import com.shop.item.api.service.ISolrService;
import com.shop.item.api.util.Command;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SolrService extends BaseService implements ISolrService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SolrService.class);
    @Autowired
    private SolrClient client;

    @Override
    public ServiceBean<String> fullImport() {
        try {
            SolrRequest<QueryResponse> request = buildRequest(Command.FULL_IMPORT, "item_base");
            request.setPath("/dataimport");
            NamedList<Object> resp = client.request(request, "");
            LOGGER.info("product 重建索引成功，具体结果:" + resp.toString());
        } catch (Exception e) {
            LOGGER.info("product 重建索引成功，异常信息:" + e.getMessage());
            e.printStackTrace();
        }
        return resultSuccess();
    }

    private SolrRequest<QueryResponse> buildRequest(Command command, String entity) {
        Map<String, String> map = new HashMap<>();
        switch (command) {
            case DELTA_IMPORT:
                map.put("command", "delta-import");
                map.put("clean", "false");
                map.put("commit", "true");
                map.put("optimize", "false");
                map.put("index", "false");
                map.put("entity", entity);
                map.put("debug", "false");
                map.put("wt", "json");
                return new QueryRequest(new MapSolrParams(map));
            case FULL_IMPORT:
                map.put("command", "full-import");
                map.put("clean", "true");
                map.put("commit", "true");
                map.put("optimize", "false");
                map.put("entity", entity);
                map.put("index", "false");
                map.put("debug", "false");
                map.put("wt", "json");
                return new QueryRequest(new MapSolrParams(map));
        }
        return null;
    }

    @Override
    public ServiceBean<List<ItemBaseOutput>> selectItemList(InputBean<ItemBaseInput> inputBean, List<String> sorts) {
        ItemBase itemBase = inputBean.getParam();
        try {
            SolrQuery params = new SolrQuery();
            if (itemBase != null) {
                Field[] fields = ItemBase.class.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    String fieldValue = field.get(itemBase) == null ? null : field.get(itemBase) + "";
                    if (StringUtils.isNotBlank(fieldValue)){
                        String p = params.get("q");
                        if (StringUtils.isNotBlank(p)){
                            p=p+" and "+fieldName + ":" + fieldValue;
                        }else{
                            p=fieldName + ":" + fieldValue;
                        }
                        params.set("q", p);
                    }

                }

                ItemBaseInput itemBaseInput = inputBean.getParam();
                //过滤条件
                if (itemBaseInput.getStartTimeStr() != null) {
                    String startDate = itemBaseInput.getStartTimeStr();
                    String endDate = itemBaseInput.getEndTimeStr();
                    startDate = StringUtils.isBlank(startDate) ? "*" : startDate + "T00:00:00Z";
                    endDate = StringUtils.isBlank(endDate) ? "*" : endDate + "T00:00:00Z";
                    params.set("fq", "createTime:[" + startDate + " TO " + endDate + "]");
                }
                if (itemBase.getSchoolId()!=null){
                    params.set("fq", "schoolId:"+itemBase.getSchoolId());
                }
                if (itemBase.getCtgName()!=null){
                    params.set("fq", "schoolId:"+itemBase.getSchoolId(),"ctgName:"+itemBase.getCtgName());
                }
            }else {
                params.set("q","*:*");
            }
            //排序
//            params.addSort("createTime", SolrQuery.ORDER.asc);
            for (String sort : sorts) {
                if ("sellingPrice".equals(sort)){
                    params.addSort("sellingPrice",SolrQuery.ORDER.asc);
                }else{
                    params.addSort(sort, SolrQuery.ORDER.desc);
                }
            }
            //分页
            if (inputBean.getIndex()!=null){
                params.setStart((inputBean.getIndex() - 1) * inputBean.getPageSize());
                params.setRows(inputBean.getPageSize());
            }
            QueryResponse queryResponse = client.query(params);
            SolrDocumentList results = queryResponse.getResults();
            List<ItemBaseOutput> resultList = new ArrayList<>();

            for (SolrDocument solrDocument : results) {
                ItemBaseOutput itemBaseOutput = JSON.parseObject(JSON.toJSONString(solrDocument), new TypeReference<ItemBaseOutput>() {
                });
                resultList.add(itemBaseOutput);
            }
            long numFound = results.getNumFound();
            ServiceBean<List<ItemBaseOutput>> serviceBean = new ServiceBean<>(resultList);
            serviceBean.setMaxSize(numFound);
            return serviceBean;
        } catch (Exception e) {
            e.printStackTrace();
            return resultFailed();
        }
    }
}
